package main

/*
#include "../IQHello.h"
#include <stdlib.h> // for free()
*/
import "C"
import (
	"runtime/cgo"
	"unsafe"
)

type IQHelloImpl struct {
	message string
	cstr    *C.char // 保存C字符串，以便后续释放
}

//export impl_t
func impl_t() C.IQImplType {
	return C.IQ_IMPL_C
}

//export createIQHello
func createIQHello() *C.IQHello {
	impl := &IQHelloImpl{
		message: "Hello, World!(Go)",
		cstr:    nil,
	}
	// 创建cgo.Handle并返回其整数值作为指针
	pinned := cgo.NewHandle(impl)
	return (*C.IQHello)(unsafe.Pointer(pinned))
}

//export deleteIQHello
func deleteIQHello(p *C.IQHello) {
	// 从指针恢复handle并获取Go对象
	pinned := cgo.Handle(unsafe.Pointer(p))
	impl := pinned.Value().(*IQHelloImpl)
	if impl.cstr != nil {
		C.free(unsafe.Pointer(impl.cstr))
	}
	pinned.Delete()
}

//export getHello
func getHello(p *C.IQHello) *C.char {
	pinned := cgo.Handle(unsafe.Pointer(p))
	impl := pinned.Value().(*IQHelloImpl)

	// 释放之前分配的字符串
	if impl.cstr != nil {
		C.free(unsafe.Pointer(impl.cstr))
	}

	// 创建新的C字符串并保存引用
	impl.cstr = C.CString(impl.message)

	return impl.cstr // 返回const char*兼容的指针
}

//go:generate go build -buildmode=c-shared -o libhello_go.so impl.go
//go:generate mkdir -p ../../build/plugins/
//go:generate cp libhello_go.so ../../build/plugins/
func main() {}
